package org.ht.demo.openapi.util;

import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.List;

public class PolygonUtil {

    /**
     * 判断点是否在多边形内部（环形）
     * @param point 要判断的点
     * @param polygon 多边形的顶点列表，按顺序排列
     * @return 如果点在多边形内部，返回true；否则返回false
     */
    public static boolean isPointInPolygon(Point2D point, List<Point2D> polygon) {
        int crossings = 0;
        int j = polygon.size() - 1;  // 最后一个顶点的索引

        for (int i = 0; i < polygon.size(); i++) {
            if ((polygon.get(i).getY() < point.getY() && polygon.get(j).getY() >= point.getY()
                    || polygon.get(j).getY() < point.getY() && polygon.get(i).getY() >= point.getY())
                    && (polygon.get(i).getX() <= point.getX() || polygon.get(j).getX() <= point.getX())) {

                double x = (point.getY() - polygon.get(j).getY()) * (polygon.get(i).getX() - polygon.get(j).getX())
                        / (polygon.get(i).getY() - polygon.get(j).getY()) + polygon.get(j).getX();

                if (x < point.getX()) {
                    crossings++;
                }
            }
            j = i;
        }

        return (crossings % 2) == 1;
    }

    public static void main(String[] args) {
        List<Point2D> polygon = new ArrayList<>();
        // 示例多边形顶点（这里是一个矩形）
        polygon.add(new Point2D.Double(116.514805,39.982375));
        polygon.add(new Point2D.Double(116.499935,40.013710));
        polygon.add(new Point2D.Double(116.546520,40.030443));
        polygon.add(new Point2D.Double(116.687668,40.129961)); // 闭合多边形
        polygon.add(new Point2D.Double(116.539697,40.080659)); // 闭合多边形

        polygon.add(new Point2D.Double(116.503390,40.058474)); // 闭合多边形

        polygon.add(new Point2D.Double(116.468800,40.052578)); // 闭合多边形

        Point2D testPointInside = new Point2D.Double(116.552884,40.034935);

        System.out.println("Is " + testPointInside + " inside the polygon? " + isPointInPolygon(testPointInside, polygon));
    }

}
